package com.zy.je.common.core.model;

import com.zy.je.common.core.constant.SysConstant;
import com.zy.je.common.core.utils.Builder;
import com.zy.je.common.core.utils.CheckUtil;
import com.zy.je.common.core.utils.collect.ListUtil;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author zy
 */
public class MatchData<T> {
    /**
     * 最终匹配成功的key
     */
    private String matchedKey;
    /**
     * 匹配到的数据
     */
    private T data;

    /**
     * 匹配的key次序
     */
    private List<String> matchTrace = ListUtil.newArrayList();

    public void setMatchedKey(String key) {
        matchTrace.add(key);
        this.matchedKey = key;
    }

    public String getMatchedKey() {
        return matchedKey;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    static public <V> MatchData<V> build(String matchedKey, V data) {
        return Builder.of(MatchData<V>::new)
                .with(MatchData::setData, data)
                .with(MatchData::setMatchedKey, matchedKey)
                .build();
    }

    static public <T> MatchData<T> getIfNoneUseDefaultKey(Map<String, T> map, String key) {
        MatchData<T> data = new MatchData();
        if (null != map) {
            data.setMatchedKey(key);
            T retData = map.get(key);
            if (null == retData) {
                retData = map.get(SysConstant.Defult.ALL.getValue());
                data.setMatchedKey(SysConstant.Defult.ALL.getValue());
            }
            data.setData(retData);
        }
        return data;
    }

    static public <T> MatchData<T> getFirstMatch(Map<String, T> map, Collection<String> keyList) {
        MatchData<T> data = new MatchData();
        if (null != map) {
            for (String key : keyList) {
                T retData = map.get(key);
                if (!CheckUtil.isBlank(retData)) {
                    data.setMatchedKey(key);
                    data.setData(retData);
                    break;
                }
            }
        }
        return data;
    }
}
